import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { getToken, clearUserChache } from '@/utils/myAuth'
import router from '@/router'
// 创建axios的实例对象
// 可以通过配置覆盖默认配置
const service = axios.create({
  // 代理可以自动拼接项目部署到本地的时候会用到baseURL
  // baseURL:'http://localhost'
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // 跨域,而且是session+cookies登陆,必须默认携带cookies对象
  timeout: 5000 // 超时时间
})

// interceptors 拦截器
service.interceptors.request.use(
  config => {
    // 检查是否由token,有的话带上token

    if (getToken() !== null && getToken() !== 'undefined') {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // 后台token无效 应该返回一个20002的状态 预留

    if (res.code === 20002) {
      Message({
        message: '登陆失效,请重新登陆!',
        type: 'error',
        duration: 5 * 1000
      })

      //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      //     // to re-login
      //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
      //       confirmButtonText: 'Re-Login',
      //       cancelButtonText: 'Cancel',
      //       type: 'warning'
      //     }).then(() => {
      //       store.dispatch('user/resetToken').then(() => {
      //         location.reload()
      //       })
      //     })
      //   }
      // 销毁证据
      clearUserChache()
      // 跳转登录页
      router.push('/login')
      return Promise.reject('Error')
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 判断传入的对象是否为空
function http(options){
  var axiosConfig={
    url:options.url,
    method:options.method
  }

  // 如果传入数据
  if(options.data){
    // 判断data的key是否为空利用对象判断
    if(Object.keys(options.data).length>0){
      axiosConfig.data=options.data
    }
  }
  return service(axiosConfig)
}

export default http
